package com.mokio.service.impl;

import com.mokio.entity.Carshop;
import com.mokio.entity.Orderdetail;
import com.mokio.entity.ProductInfo;
import com.mokio.entity.Xmorder;
import com.mokio.mapper.OrderdetailMapper;
import com.mokio.mapper.ProductInfoMapper;
import com.mokio.mapper.XmorderMapper;
import com.mokio.service.XmorderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @program: xiaomishop
 * @ClassName XmorderServiceImpl
 * @description:
 * @author: mokio
 * @create: 2024−12-21 10:53
 * @Version 1.0
 **/
@Service
public class XmorderServiceImpl implements XmorderService {

    @Autowired
    private XmorderMapper xmorderMapper;

    @Autowired
    private OrderdetailMapper orderdetailMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Override
    public int save(Xmorder xmorder, String[] pids, List<Carshop> carshopList) {
        int num=0;

        //保存订单
        xmorderMapper.insertSelective(xmorder);
        //将商品的 信息存入到订单明细中
        for(String pidd:pids){
            //拿到商品编号
            int pid = Integer.parseInt(pidd);
            for(Carshop c:carshopList){
                if(pid!=c.getProd().getpId()){
                    continue;
                }
                //订单明细
                Orderdetail orderdetail = new Orderdetail();
                orderdetail.setOid(xmorder.getOid());//订单明细所属 的订单编号
                orderdetail.setPid(c.getProd().getpId());
                orderdetail.setPnumber(c.getNumbers());
                //小计
                orderdetail.setPtotal(c.getProd().getpPrice()* c.getNumbers()*1.0);
                //添加订单明细
                orderdetailMapper.insertSelective(orderdetail);

                //扣减库存
                ProductInfo productInfo= c.getProd();
                Integer getpId = productInfo.getpId();

                Integer numberold = productInfoMapper.selectByPrimaryKey(getpId).getpNumber();

                Integer numbers = c.getNumbers();
                System.out.println();
                productInfo.setpNumber(numberold-c.getNumbers());

                productInfoMapper.updateByPrimaryKey(productInfo);

                //没有出错
                num=1;


            }
        }




        return num;
    }

    @Override
    public List<Xmorder> findOrdersByUserId(Integer uid) {
        return xmorderMapper.selectAllById(uid);
    }
}
